package util

import (
	"frontend-server/global"
	"time"

	"github.com/dgrijalva/jwt-go"
)

type UserJwtClaims struct {
	ID       uint   `json:"id"`
	Username string `json:"username"`
	jwt.StandardClaims
}

// 生成 Token
func GenerateToken(id uint, username string) (string, error) {
	cliams := UserJwtClaims{
		ID:       id,
		Username: username,
		StandardClaims: jwt.StandardClaims{
			// 过期时间
			ExpiresAt: time.Now().Add(2 * time.Hour).Unix(),
			// 当前时间
			IssuedAt: time.Now().Unix(),
			// 签发者
			Issuer: global.App.Config.JWT.Issuer,
			// 签发主题
			Subject: global.App.Config.JWT.Subject,
		},
	}
	ts := jwt.NewWithClaims(jwt.SigningMethodHS256, cliams)
	return ts.SignedString([]byte(global.App.Config.JWT.Secret))
}

// 验证 Token
func VerifyToken(token string) (*UserJwtClaims, bool) {
	tokenObj, _ := jwt.ParseWithClaims(token, &UserJwtClaims{}, func(t *jwt.Token) (interface{}, error) {
		return []byte(global.App.Config.JWT.Secret), nil
	})
	if key, _ := tokenObj.Claims.(*UserJwtClaims); tokenObj.Valid {
		return key, true
	} else {
		return nil, false
	}
}
